<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

class f_builder_ModuleBuilder
{
	private $moduleName;
	private $folders = array("actions","actions/block", "config", "documents", "forms", "services", "install", "sql", "locales", "templates", "templates/block", "patchs", "views", "views/block");
	
	/**
	 * @return f_builder_ModuleBuilder
	 */
	public static function getInstance()
	{
		return new self();
	}
	
	/**
	 * @param string $value
	 * @return f_builder_ModuleBuilder
	 */
	public function setModuleName($value)
	{
		$this->moduleName = $value;
		return $this;
	}
	
	/**
	 * Build a new module folder structure
	 *
	 * @param string $moduleDir
	 */
	public function createModule($moduleDir = MODULES_DIR)
	{
		if(is_string($this->moduleName))
		{
			$modulePath = $moduleDir.DS.$this->moduleName;
			
			foreach($this->folders as $path)
			{
				$mPath = $modulePath.DS.$path;
				if(!is_dir($mPath))
				{					
					$pathCreation = mkdir($mPath, 0755, true);
					
					if($pathCreation)
					{
						echo COLOR_GREEN."Writing".COLOR_NORMAL." -> create path $mPath\n";
					}
				}
				else
				{
					echo COLOR_RED."Skipped".COLOR_NORMAL." -> path $mPath already exists, remove if necessary\n";
				}
			}

            if($this->buildPackageFile($modulePath))
            {
                echo COLOR_GREEN."Writing".COLOR_NORMAL." -> building package file\n";
            }

            f_package_Manager::getInstance()->initOrUpgradePackageByLabel('extension_module_'.$this->moduleName);
		}
		else
		{
			throw new Exception("Module name is not set");
		}
	}

    private function buildPackageFile($modulePath)
    {
        $tpl = f_template_Template::getInstance()->setTemplate(FRAMEWORK_HOME.DS.'builder'.DS.'defaultdocuments'.DS.'modulePackage.xml');
        $tpl->assign('name', $this->moduleName);
        $tpl = $tpl->render();

        $file = fopen($modulePath.DS.'package.xml', 'w+');

        fwrite($file, $tpl);

        fclose($file);

        return true;
    }
}